<template>
    <div class="pagination">
        <button :disabled='pageNo==1' @click="$emit('currentPage', pageNo-1)">上一页</button>
        <button v-show="startAndEndNum.start>=2" @click="$emit('currentPage', 1)">1</button>

        <button v-show="startAndEndNum.start>2">···</button>

        <button v-for="(page, index) in startAndEndNum.end" :key="index" v-show="page>=startAndEndNum.start"
            :class="{active:pageNo==page}" @click="$emit('currentPage', page)">{{page}}</button>

        <button v-show="startAndEndNum.end<totalPage-1">···</button>
        <button v-show="startAndEndNum.end<totalPage" @click="$emit('currentPage', totalPage)">{{totalPage}}</button>
        <button :disabled='pageNo==totalPage' @click="$emit('currentPage', pageNo+1)">下一页</button>

        <button style="margin-left: 30px">共 {{total}} 条</button>
    </div>
</template>

<script>
    export default {
        name: 'Pagination',
        //total:商品数量 pageSize:每页展示数量 pageNo:当前页数 cotinues:分页器连续页数
        props: ['total', 'pageSize', 'pageNo', 'continues'],
        computed: {
            //计算需要总共多少页数
            totalPage() {
                return Math.ceil(this.total / this.pageSize);
            },
            //开始和结束的页数
            startAndEndNum() {
                let {
                    pageNo,
                    continues,
                    totalPage
                } = this;
                let start = pageNo - parseInt(continues / 2);
                let end = pageNo + parseInt(continues / 2);

                //如果开始页数小于第一页，置为1，结束页数为分页器最大长度
                if (start < 1) {
                    start = 1;
                    end = continues;
                }

                //如果结束页数超过最大页数，则置为最大页数，开始页数为最大页数-分页器长度+1
                if (end > totalPage) {
                    end = totalPage;
                    start = totalPage - continues + 1;
                }
                return {
                    start,
                    end
                }
            }
        }
    }
</script>

<style lang="less" scoped>
    .pagination {
        text-align: center;

        button {
            margin: 0 5px;
            background-color: #f4f4f5;
            color: #606266;
            outline: none;
            border-radius: 2px;
            padding: 0 4px;
            vertical-align: top;
            display: inline-block;
            font-size: 13px;
            min-width: 35.5px;
            height: 28px;
            line-height: 28px;
            cursor: pointer;
            box-sizing: border-box;
            text-align: center;
            border: 0;

            &[disabled] {
                color: #c0c4cc;
                cursor: not-allowed;
            }

            &.active {
                cursor: not-allowed;
                background-color: #409eff;
                color: #fff;
            }
        }
    }
</style>